<template>
  <j-modal
    :title="title"
    :width="width"
    :visible="visible"
    :confirmLoading="confirmLoading"
    switchFullscreen
    @ok="handleOk"
    @cancel="handleCancel"
    :ok-button-props="{ props: { disabled: disableSubmit } }"
    cancelText="关闭">
    <template slot="footer">
      <a-button @click="handleCancel">关闭</a-button>
      <a-button v-if="!disableSubmit" type="primary" @click="handleOk" :loading="buttonok">确定</a-button>
    </template>
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-row>

          <a-col :span="12">
            <a-form-item label="合同名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['name']" :disabled="disableSubmit" placeholder="请输入合同名称"></a-input>
            </a-form-item>
          </a-col>
           <a-col :span="12">
            <a-form-item label="合同模板名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-dict-select-tag type="list" :disabled="disableSubmit" @change="selectChange"
                                 v-decorator="['templateId',validatorRules.templateId]" :trigger-change="true"
                                 dictCode="ClmTemplate,name,id, statusId = 2 & typeId = labor" placeholder="请选择合同模板"/>
            </a-form-item>
          </a-col>
          <!-- <a-col :span="12">
          <a-form-item label="关键字" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a-select
              mode="tags"
              style="width: 100%"
              :token-separators="[',']"
              :disabled="disableSubmit"
              v-decorator="['keywords', validatorRules.keywords]"
              placeholder="请输入[盖章,签约日期]关键字,以英文逗号间隔"
            >
            </a-select>
          </a-form-item>
          </a-col> -->
          <!-- <a-col :span="12">
            <a-form-item label="补充商业保险" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-dict-select-tag :disabled="disableSubmit" type="list"
                                 v-decorator="['isInsurance', validatorRules.isInsurance]"
                                 :trigger-change="true"
                                 dictCode="DataDictionary,description,dictionaryCode, dictionaryTypeId = BOOL_DEFINE"
                                 placeholder="请选择"/>
            </a-form-item>
          </a-col> -->
          <a-col :span="12">
            <a-form-item label="甲方" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-search-select-tag v-if="fromCompanyTypeId == 'PERSON'" :disabled="disableSubmit"
                                   :async="false"
                                   @change="generateCode"
                                   dict="Person,name,partyId,typeId=EMPLOYEE"
                                   v-decorator="['fromCompanyId',validatorRules.fromCompanyId]"
                                   :trigger-change="true"
                                   placeholder="请选择甲方"
              />

              <j-search-select-tag v-else-if="fromCompanyTypeId == 'GROUP'" :disabled="disableSubmit"
                                   :async="false"
                                   @change="generateCode"
                                   dict="ClmCompany,companyName,id,statusId=2 & typeId=Internal & isShow=Y"
                                   v-decorator="['fromCompanyId',validatorRules.fromCompanyId]"
                                   :trigger-change="true"
                                   placeholder="请选择甲方"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="乙方" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-search-select-tag v-if="toCompanyTypeId == 'PERSON'" :disabled="disableSubmit"
                                   :async="false"
                                   @change="getYiInfo"
                                   dict="Person,name,partyId,typeId=EMPLOYEE"
                                   v-decorator="['toCompanyId',validatorRules.toCompanyId]"
                                   :trigger-change="true"
                                   placeholder="请选择乙方"
              />
              <j-search-select-tag v-else-if="toCompanyTypeId == 'GROUP'" :disabled="disableSubmit"
                                   :async="false"
                                   dict="ClmCompany,companyName,id,statusId=2"
                                   v-decorator="['toCompanyId',validatorRules.toCompanyId]"
                                   :trigger-change="true"
                                   placeholder="请选择乙方"
              />
            </a-form-item>
          </a-col>
           <a-col :span="12">
            <a-form-item label="合同编号" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['agreementCode']" :disabled="disableSubmit" placeholder="请输入合同编号"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="签约时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-date placeholder="请选择签约时间" :disabled="disableSubmit" v-decorator="['signDate',validatorRules.signDate]"
                      :trigger-change="true" :show-time="true"  style="width: 100%"/>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="合同备注" :labelCol="{ xs: { span: 24 }, sm: { span: 4 }}"
                         :wrapperCol="{ xs: { span: 24 }, sm: { span: 20 }}">
              <a-textarea placeholder="请输入备注" :disabled="disableSubmit"
                          v-decorator="['description']"/>
            </a-form-item>
          </a-col>
          <!-- <a-col :span="12">
            <a-form-item label="合同生效时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-date placeholder="请选择合同生效时间" :disabled="disableSubmit" v-decorator="['fromDate']"
                      :trigger-change="true"  style="width: 100%"/>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="合同到期时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-date placeholder="请选择合同到期时间" :disabled="disableSubmit" v-decorator="['thruDate']"
                      :trigger-change="true"  style="width: 100%"/>
            </a-form-item>
          </a-col> -->
          <a-col :span="12" v-for="item in itemList" :key="item.id">
            <a-form-item :label="item.name" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input :disabled="disableSubmit"
                       v-if="item.fieldTypeId == '1'"
                       v-model="item.description"
                       :placeholder="'请输入' + item.name"
              ></a-input>
              <j-date :disabled="disableSubmit"
                      v-if="item.fieldTypeId == '2'"
                      :placeholder="'请选择' + item.name"
                      v-model="item.description"
                      :trigger-change="true"
                      style="width: 100%"
              />
              <!--
                <j-dict-select-tag type="list" :disabled="disableSubmit" v-model="item.description" v-if="item.fieldTypeId == '3'"
                 :trigger-change="true" :dictCode="item.entityId+',description,dictionaryCode, dictionaryTypeId = '+item.dictionaryTypeId" :placeholder="'请选择'+item.name"/>
              -->
              <j-dict-select-tag type="list"
                                 :disabled="disableSubmit"
                                 v-model="item.description"
                                 v-if="item.fieldTypeId == '3'"
                                 :dictCode="item.entityId+',description,dictionaryCode, dictionaryTypeId = '+item.dictionaryTypeId"
                                 :placeholder="'请选择'+item.name"/>
              <j-image-upload
                  v-if="item.fieldTypeId == '5'"
                  :disabled="disableSubmit"
                  :isMultiple="false"
                  v-model="item.description"
                ></j-image-upload>
            </a-form-item>
          </a-col>

        </a-row>
      </a-form>
    </a-spin>
  </j-modal>
</template>

<script>

  import {httpAction, getAction} from '@/api/manage'
  import pick from 'lodash.pick'
  import {validateDuplicateValue} from '@/utils/util'
  import JDate from '@/components/jeecg/JDate'
  import JDictSelectTag from "@/components/dict/JDictSelectTag"
  import JSearchSelectTag from '../../../../../components/dict/JSearchSelectTag'
  import JImageUpload from '@/components/jeecg/JImageUpload'
  import ATextarea from "ant-design-vue/es/input/TextArea";

  export default {
    name: "ClmAgreementModal",
    components: {
      ATextarea,
      JDate,
      JDictSelectTag,
      JSearchSelectTag,
      JImageUpload
    },
    data () {
      return {
        disableSubmit: false,
        form: this.$form.createForm(this),
        title: "操作",
        width: 1000,
        visible: false,
        buttonok: false,
        model: {},
        itemList: [],
        newItemList: [],
        ClmAgreementItem: [],
        labelCol: {
          xs: {span: 24},
          sm: {span: 8},
        },
        wrapperCol: {
          xs: {span: 24},
          sm: {span: 16},
        },
        confirmLoading: false,
        validatorRules: {
          templateId: {
            rules: [
              {required: true, message: '请选择合同模板名称!'},
            ]
          },
          signDate: {
            rules: [
              {required: true, message: '请选择签约时间!'},
            ]
          },
          fromCompanyId: {
            rules: [
              {required: true, message: '请选择甲方!'},
            ]
          },
          toCompanyId: {
            rules: [
              {required: true, message: '请选择乙方!'},
            ]
          },
          keywords: {
            rules: [{required: true, message: '请输入盖章关键字!'}],
          },
        },
        url: {
          add: "/online/special/api/createClmAgreement",
          edit: "/online/special/api/updateClmAgreement",
          get: "/online/api/getClmAgreement",
          getClmTemplateAndItem: "/online/api/getClmTemplateAndItem",
          selectDataDictionary: "/online/api/selectDataDictionary",
          getEmploymentAgreementCode: "/online/api/getEmploymentAgreementCode",
          getCompany: "/online/api/getClmCompany",
          getHrEmployee: "/online/api/getHrEmployee",
        },
        fromCompanyTypeId: 'GROUP',
        toCompanyTypeId: 'PERSON',
      }
    },
    created () {
    },
    methods: {
      add () {
        this.edit({});
      },
      edit (record) {
        this.itemList = []
        this.form.resetFields();
        this.visible = true;
        this.model = {};
        if (record.id) {
          httpAction(this.url.get, {id: record.id}, "post").then((res) => {
            if (res.success) {
              this.model = Object.assign({}, res.result);
              if (this.model.keywords) {
                this.model.keywords = this.model.keywords.replace("[", "");
                this.model.keywords = this.model.keywords.replace("]", "");
                this.model.keywords = this.model.keywords.split(',');
              }
              delete this.model['newItemList'];
              this.newItemList = res.result.itemList;
              if (this.newItemList) {
                let itemList = [];
                this.newItemList.forEach(item => {
                  itemList.push({
                    fieldTypeId: item.fieldTypeId, description: item.description,
                    name: item.name, entityId: item.entityId, dictionaryTypeId: item.dictionaryTypeId
                  })
                })
                this.itemList = itemList;
              }
              if (this.model.fromCompanyTypeId) this.fromCompanyTypeId = this.model.fromCompanyTypeId;
              if (this.model.toCompanyTypeId) this.toCompanyTypeId = this.model.toCompanyTypeId;
              this.$nextTick(() => {
                this.form.setFieldsValue(pick(this.model, 'name','description','agreementCode', 'templateId', 'typeId', 'specificTypeId', 'fromCompanyId', 'toCompanyId', 'signDate', 'agreementAmount', 'fromDate', 'thruDate', 'createDate', 'createBy', 'statusId', 'keywords'))
              })
            }
          })
        }
      },
      close () {
        this.$emit('close');
        this.visible = false;
      },
      handleOk () {
        const that = this;
        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err) {
            that.confirmLoading = true;
            that.buttonok = true
            let httpurl = '';
            let method = '';
            if (!this.model.id) {
              httpurl += this.url.add;
              method = 'post';
              this.model.statusId = '0';
            } else {
              httpurl += this.url.edit;
              method = 'put';
            }
            if (this.fromCompanyTypeId) this.model.fromCompanyTypeId = this.fromCompanyTypeId;
            if (this.toCompanyTypeId) this.model.toCompanyTypeId = this.toCompanyTypeId;

            this.model.typeId = 'labor';
            this.model.specificTypeId = 'labor';
            let isOk = true;
            let formData = Object.assign(this.model, values);
            formData.isInsurance = 'N';
            if (this.itemList) {
              this.ClmAgreementItem = [];
              this.itemList.forEach(item => {
                this.ClmAgreementItem.push({
                  name: item.name,
                  description: item.description,
                  fieldTypeId: item.fieldTypeId,
                  entityId: item.entityId,
                  dictionaryTypeId: item.dictionaryTypeId
                })

                if(!item.description){
                  that.$message.error("请输入"+item.name);
                  isOk = false;
                }
              })
              formData.ClmAgreementItem = this.ClmAgreementItem;
            }
            if(isOk == true){
              httpAction(httpurl, formData, method).then((res) => {
                if (res.success) {
                  that.$message.success('提交成功!');
                  that.$emit('ok');
                } else {
                  that.$message.warning(res.message);
                }
                setTimeout(() => {
                  that.buttonok = false;
                }, 500);
              }).finally(() => {
                that.confirmLoading = false;
                that.close();
              })
            }else{
              that.buttonok = false
              that.confirmLoading = false;
            }

          }

        })
      },
      handleCancel () {
        this.close()
      },
      popupCallback(row){
        this.form.setFieldsValue(pick(row, 'name','description', 'agreementCode', 'templateId', 'typeId', 'specificTypeId', 'fromCompanyId', 'toCompanyId', 'signDate', 'agreementAmount', 'fromDate', 'thruDate', 'createDate', 'createBy', 'statusId', 'keywords'))
      },
      selectChange(e){
        if (e == undefined) {
          return false
        } else {
          getAction(this.url.getClmTemplateAndItem, {id: e}).then(res => {
            if (res.success) {
              let itemList = res.result.clmTemplateItemList.reverse();
              itemList.forEach((item) => {
                if (item.itemDefaultValue) {
                  item.description = item.itemDefaultValue
                }
              })
              this.itemList = itemList
              let fromCompanyId = this.form.getFieldValue('fromCompanyId')
              let toCompanyId = this.form.getFieldValue('toCompanyId')
              this.generateCode(fromCompanyId)
              this.getYiInfo(toCompanyId)
            }
          })
          
        }
      },
      generateCode(e){
        let that = this;
        getAction(that.url.getEmploymentAgreementCode, {fromCompanyId: e}).then(res => {
          if (res.success) {
            that.model.agreementCode = res.result.agreementCode;
            that.$nextTick(() => {
              that.form.setFieldsValue(
                pick(
                  that.model,
                  'agreementCode',
                )
              )
            })
          }
        });
        if(e){
          getAction(that.url.getCompany,{typeId: 'Internal',id: e}).then(res2 => {
            if(res2.success){
              let companyInfo = res2.result;
              that.itemList.forEach(item => {
                if(item.name == '公司名称'){
                  item.description = companyInfo.companyName ? companyInfo.companyName : ''
                }
                if(item.name == '公司法定代表人'){
                  item.description = companyInfo.legalName ? companyInfo.legalName : ''
                }
                if(item.name == '公司注册地址'){
                  item.description = companyInfo.invoiceAddress ? companyInfo.invoiceAddress : ''
                }
                if(item.name == '公司联系地址'){
                  item.description = companyInfo.detailedAddress ? companyInfo.detailedAddress : ''
                }
                if(item.name == '公司联系电话'){
                  item.description = companyInfo.companyPhone ? companyInfo.companyPhone : ''
                }
                if(item.name == '公司邮政编码'){
                  item.description = companyInfo.postCode ? companyInfo.postCode : ''
                }
              })
              this.$nextTick(() => {
                that.$forceUpdate();
              })

            }
          });
        }
      },
      getYiInfo(e){
        let that = this;
        if(e){
          getAction(that.url.getHrEmployee,{typeId: 'EMPLOYEE',partyId: e}).then(res2 => {
            if(res2.success){
              let personInfo = res2.result;
              that.itemList.forEach(item => {
                if(item.name == '员工姓名'){
                  item.description = personInfo.name ? personInfo.name : ''
                }
                if(item.name == '员工性别'){
                  item.description = personInfo.gender ? personInfo.gender : ''
                }
                if(item.name == '员工身份证号码'){
                  item.description = personInfo.idCard ? personInfo.idCard : ''
                }
                if(item.name == '员工联系地址'){
                  item.description = personInfo.address ? personInfo.address : ''
                }
                if(item.name == '员工邮政编码'){
                  item.description = personInfo.postCode ? personInfo.postCode : ''
                }
                if(item.name == '员工联系电话'){
                  item.description = personInfo.phone ? personInfo.phone : ''
                }
                if(item.name == '紧急联系人姓名'){
                  item.description = personInfo.emergencyContact ? personInfo.emergencyContact : ''
                }
                if(item.name == '紧急联系人电话'){
                  item.description = personInfo.contactNumber ? personInfo.contactNumber : ''
                }
              })
              this.$nextTick(() => {
                that.$forceUpdate();
              })

            }
          });
        }
      },
    }
  }
</script>
